package com.android.stm;




import javax.microedition.khronos.opengles.GL10;

import org.anddev.andengine.engine.Engine;
import org.anddev.andengine.engine.camera.Camera;
import org.anddev.andengine.engine.handler.timer.ITimerCallback;
import org.anddev.andengine.engine.handler.timer.TimerHandler;
import org.anddev.andengine.engine.options.EngineOptions;
import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation;
import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy;
import org.anddev.andengine.entity.IEntity;

import org.anddev.andengine.entity.modifier.LoopEntityModifier;
import org.anddev.andengine.entity.modifier.PathModifier;
import org.anddev.andengine.entity.modifier.PathModifier.IPathModifierListener;
import org.anddev.andengine.entity.modifier.PathModifier.Path;

import org.anddev.andengine.entity.particle.ParticleSystem;
import org.anddev.andengine.entity.particle.emitter.CircleOutlineParticleEmitter;
import org.anddev.andengine.entity.particle.initializer.AlphaInitializer;
import org.anddev.andengine.entity.particle.initializer.ColorInitializer;
import org.anddev.andengine.entity.particle.initializer.RotationInitializer;
import org.anddev.andengine.entity.particle.initializer.VelocityInitializer;
import org.anddev.andengine.entity.particle.modifier.AlphaModifier;
import org.anddev.andengine.entity.particle.modifier.ColorModifier;
import org.anddev.andengine.entity.particle.modifier.ExpireModifier;
import org.anddev.andengine.entity.particle.modifier.ScaleModifier;
import org.anddev.andengine.entity.scene.Scene;
import org.anddev.andengine.entity.scene.Scene.IOnSceneTouchListener;
import org.anddev.andengine.entity.scene.background.AutoParallaxBackground;
import org.anddev.andengine.entity.scene.background.ColorBackground;
import org.anddev.andengine.entity.scene.background.ParallaxBackground.ParallaxEntity;
import org.anddev.andengine.entity.sprite.AnimatedSprite;
import org.anddev.andengine.entity.sprite.Sprite;
import org.anddev.andengine.entity.text.ChangeableText;
import org.anddev.andengine.entity.util.FPSCounter;
import org.anddev.andengine.entity.util.FPSLogger;
import org.anddev.andengine.input.touch.TouchEvent;
import org.anddev.andengine.opengl.font.Font;
import org.anddev.andengine.opengl.texture.TextureOptions;
import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas;
import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory;
import org.anddev.andengine.opengl.texture.atlas.bitmap.BuildableBitmapTextureAtlas;
import org.anddev.andengine.opengl.texture.atlas.bitmap.source.IBitmapTextureAtlasSource;
import org.anddev.andengine.opengl.texture.buildable.builder.BlackPawnTextureBuilder;
import org.anddev.andengine.opengl.texture.buildable.builder.ITextureBuilder.TextureAtlasSourcePackingException;
import org.anddev.andengine.opengl.texture.region.BaseTextureRegion;
import org.anddev.andengine.opengl.texture.region.TextureRegion;
import org.anddev.andengine.opengl.texture.region.TiledTextureRegion;

import org.anddev.andengine.extension.input.touch.controller.MultiTouch;
import org.anddev.andengine.extension.input.touch.controller.MultiTouchController;
import org.anddev.andengine.extension.input.touch.exception.MultiTouchException;

import org.anddev.andengine.extension.svg.adt.ISVGColorMapper;
import org.anddev.andengine.extension.svg.adt.SVGDirectColorMapper;


import org.anddev.andengine.ui.activity.BaseGameActivity;
import org.anddev.andengine.util.modifier.ease.EaseSineInOut;

import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Debug;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.widget.LinearLayout;
import android.widget.Toast;

import org.anddev.andengine.extension.svg.opengl.texture.atlas.bitmap.SVGBitmapTextureAtlasTextureRegionFactory;


public class SaveTheMageActivity extends BaseGameActivity {


    private static int CAMERA_WIDTH =  480;
    private static int CAMERA_HEIGHT = 853;

    private Camera mCamera;
    private BitmapTextureAtlas mBitmapTextureAtlas;
    private BitmapTextureAtlas mBitmapTextureAtlasTer;
    private BitmapTextureAtlas mBitmapTextureAtlasBis;

    private BitmapTextureAtlas mFontTexture;
    private Font mFont;

    private TextureRegion mParticleTextureRegion;
    private TiledTextureRegion mMagoTextureRegion;

    private TextureRegion mMenuLeftTextureRegion;
    
    
    private BitmapTextureAtlas mAutoParallaxBackgroundTexture;
    private TextureRegion mParallaxLayerBack;
    private TextureRegion mParallaxLayerMid;
    private TextureRegion mParallaxLayerFront;
    
    private BaseTextureRegion mSVGTestTextureRegions, mSVGTestTextureRegionsNuage;
    private BuildableBitmapTextureAtlas mBuildableBitmapTextureAtlas, mBuildableBitmapTextureAtlasNuage, mBuildableBitmapTextureAtlasPoussin;

    private TiledTextureRegion mSVGTestTextureRegionsPoussin;

    
    private   AnimatedSprite mage, mage2;
    
    private AnimatedSprite poussin;
    
    private SceneManager sm;
    
    private Scene scene = new Scene();
    
    private Sprite backButton, menuleft;
    
    private BitmapTextureAtlas mMenuTextureAtlas; 
    
    private boolean menuPressed = true;
    

    public Engine onLoadEngine() {
    	
    		this.sm = new SceneManager(this);
    		
    		DisplayMetrics metrics = new DisplayMetrics();
    		getWindowManager().getDefaultDisplay().getMetrics(metrics);

    		CAMERA_HEIGHT = metrics.heightPixels;
    		CAMERA_WIDTH = metrics.widthPixels;
    	    this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT);
            final Engine engine = new Engine(new EngineOptions(true, ScreenOrientation.PORTRAIT, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera));

            try {
                     if(MultiTouch.isSupported(this)) {
                             engine.setTouchController(new MultiTouchController());
                             if(MultiTouch.isSupportedDistinct(this)) {
                                     Toast.makeText(this, "MultiTouch OK", Toast.LENGTH_LONG).show();
                             } else {
                                     Toast.makeText(this, "MultiTouch OK but device problem", Toast.LENGTH_LONG).show();
                             }
                     } else {
                             Toast.makeText(this, "MultiTouch NOT OK", Toast.LENGTH_LONG).show();
                     }
             } catch (final MultiTouchException e) {
                     Toast.makeText(this, "Android Version does NOT support MultiTouch", Toast.LENGTH_LONG).show();
             }

             return engine;

    }


    public void onLoadResources() {
            this.mBitmapTextureAtlas = new BitmapTextureAtlas(64, 64, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
            this.mBitmapTextureAtlasBis = new BitmapTextureAtlas(256, 256, TextureOptions.BILINEAR);
         
            
            this.mBuildableBitmapTextureAtlas = new BuildableBitmapTextureAtlas(1024,1024, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
            this.mBuildableBitmapTextureAtlasPoussin = new BuildableBitmapTextureAtlas(1024,1024, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
            this.mBuildableBitmapTextureAtlasNuage = new BuildableBitmapTextureAtlas(1024,1024, TextureOptions.BILINEAR_PREMULTIPLYALPHA);

           


            BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/");
            
          
            
          //  SVGTextureRegionFactory.createFromAsset(this.mBuildableBitmapTextureAtlas, this, "collineSVG1.svg", 16, 16);
            /****************/
            
            this.mAutoParallaxBackgroundTexture = new BitmapTextureAtlas(1024, 1024, TextureOptions.DEFAULT);
            
            this.mParallaxLayerBack = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mAutoParallaxBackgroundTexture, this, "parallax_background_layer_back.png", 0, 188);
            this.mParallaxLayerMid = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mAutoParallaxBackgroundTexture, this, "nuage.png", 0, 669);

            this.mEngine.getTextureManager().loadTextures(this.mBitmapTextureAtlas, this.mAutoParallaxBackgroundTexture);

            /*****/
          
            
            this.mParticleTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlas, 
            		this, "particule_point.png", 0, 0);
            this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlas);
            
                      
            this.mMagoTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBitmapTextureAtlasBis, 
            		this, "mago.png", 0, 0, 2, 2);
            
            this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlasBis);
            
            
            this.mFontTexture = new BitmapTextureAtlas(256, 256, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
            this.mEngine.getTextureManager().loadTexture(this.mFontTexture);

            this.mFont = new Font(this.mFontTexture, Typeface.create(Typeface.DEFAULT, Typeface.BOLD), 24, true, Color.DKGRAY);
            this.mEngine.getTextureManager().loadTexture(this.mFontTexture);
            this.mEngine.getFontManager().loadFont(this.mFont);
            
            
            /***  Fleche back   **/
            this.mMenuTextureAtlas = new BitmapTextureAtlas(64, 64, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
            this.mMenuLeftTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(mMenuTextureAtlas, this, "prev.png", 0, 0);
            this.mEngine.getTextureManager().loadTexture(mMenuTextureAtlas);
            
            
            
            
            
            SVGBitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/");
            this.mSVGTestTextureRegions = SVGBitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBuildableBitmapTextureAtlas, 
            		this, "colline1.svg", CAMERA_WIDTH, CAMERA_HEIGHT);
            try {
                this.mBuildableBitmapTextureAtlas.build(new BlackPawnTextureBuilder<IBitmapTextureAtlasSource, BitmapTextureAtlas>(1));
	        } catch (final TextureAtlasSourcePackingException e) {
	                Log.v(e+"", "svg");
	        }
            this.mEngine.getTextureManager().loadTexture(this.mBuildableBitmapTextureAtlas);
            

            
            this.mSVGTestTextureRegionsNuage = SVGBitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBuildableBitmapTextureAtlasNuage, 
            		this, "nuage.svg", CAMERA_WIDTH, CAMERA_HEIGHT/5);
            try {
                this.mBuildableBitmapTextureAtlasNuage.build(new BlackPawnTextureBuilder<IBitmapTextureAtlasSource, BitmapTextureAtlas>(1));
	        } catch (final TextureAtlasSourcePackingException e) {
	                Log.v(e+"", "svg");
	        }
            this.mEngine.getTextureManager().loadTexture(this.mBuildableBitmapTextureAtlasNuage);
            
            
            
            
            this.mSVGTestTextureRegionsPoussin = SVGBitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBuildableBitmapTextureAtlasPoussin, 
            		this, "pacdroid2.svg", 64, 128, 4, 2 );
            try {
                this.mBuildableBitmapTextureAtlasPoussin.build(new BlackPawnTextureBuilder<IBitmapTextureAtlasSource, BitmapTextureAtlas>(1));
	        } catch (final TextureAtlasSourcePackingException e) {
	                Log.v(e+"", "svg");
	        }
            
            this.mEngine.getTextureManager().loadTexture(this.mBuildableBitmapTextureAtlasPoussin);



    }

    
    public Scene onLoadScene() {
           // this.mEngine.registerUpdateHandler(new FPSLogger());
            
            final FPSCounter fpsCounter = new FPSCounter();
            this.mEngine.registerUpdateHandler(fpsCounter);


           
            
            
            final AutoParallaxBackground autoParallaxBackground = new AutoParallaxBackground(0, 0, 0, 5);
           // autoParallaxBackground.attachParallaxEntity(new ParallaxEntity(0.0f, new Sprite(0, CAMERA_HEIGHT - this.mParallaxLayerBack.getHeight(), this.mParallaxLayerBack)));
          
           //
            final BaseTextureRegion baseTextureRegion = this.mSVGTestTextureRegions;
            final TextureRegion textureRegion = (TextureRegion)baseTextureRegion;

            
            autoParallaxBackground.attachParallaxEntity(new ParallaxEntity(0.0f, new Sprite(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT, textureRegion)));
            
           // final BaseTextureRegion baseTextureRegionNuage = this.mSVGTestTextureRegionsNuage;
          //  final TextureRegion textureRegionNuage = (TextureRegion)baseTextureRegionNuage;
            
            autoParallaxBackground.attachParallaxEntity(new ParallaxEntity(-2.0f, new Sprite(0, 30, CAMERA_WIDTH, CAMERA_HEIGHT/5, mParallaxLayerMid)));
            
            scene.setBackground(autoParallaxBackground);

          //  scene.setBackground(new ColorBackground(0.5f, 0.5f, 0.5f));

         
            
            //scene.setBackground(new ColorBackground(0.09804f, 0.6274f, 0.8784f));

            
          //  final ChangeableText elapsedText = new ChangeableText(20, 160, this.mFont, "Seconds elapsed:", "Seconds elapsed: XXXXX".length());
            final ChangeableText fpsText = new ChangeableText(10, 10, this.mFont, "FPS : ", "FPS: XXXXX".length());

        //    scene.attachChild(elapsedText);
            scene.attachChild(fpsText);

            scene.registerUpdateHandler(new TimerHandler(1 / 20.0f, true, new ITimerCallback() {
                    
                    public void onTimePassed(final TimerHandler pTimerHandler) {
                          //  elapsedText.setText("Seconds elapsed: " + SaveTheMageActivity.this.mEngine.getSecondsElapsedTotal());
                            fpsText.setText("FPS : " + fpsCounter.getFPS());
                    }
            }));


            final CircleOutlineParticleEmitter particleEmitter = new CircleOutlineParticleEmitter(CAMERA_WIDTH * 0.5f, CAMERA_HEIGHT * 0.5f + 20, 10);
            final ParticleSystem particleSystem = new ParticleSystem(particleEmitter, 60, 200, 600, this.mParticleTextureRegion);

            
            mage = new AnimatedSprite(100, CAMERA_HEIGHT - 160, 40, 40, this.mMagoTextureRegion);
            
           // mage2 = new AnimatedSprite(100, CAMERA_HEIGHT - 50, this.mMagoTextureRegion);
            
           final BaseTextureRegion baseTextureRegionPoussin = this.mSVGTestTextureRegionsPoussin;
           final TiledTextureRegion textureRegionPoussin = (TiledTextureRegion)baseTextureRegionPoussin;

            poussin = new AnimatedSprite(10, 10, 20, 20,  textureRegionPoussin);
            
            scene.setOnSceneTouchListener(new IOnSceneTouchListener() {
                 
                    public boolean onSceneTouchEvent(final Scene pScene, final TouchEvent pSceneTouchEvent) {
                           // particleEmitter.setCenter(pSceneTouchEvent.getX(), pSceneTouchEvent.getY());
                            
                    	//pSceneTouchEvent.
                    	mage.setPosition(pSceneTouchEvent.getX() - mage.getBaseHeight()/2, pSceneTouchEvent.getY() - mage.getBaseWidth()/2);
                    	
                    	//poussin.setPosition(pSceneTouchEvent.getX() - poussin.getBaseHeight()/2, pSceneTouchEvent.getY() - poussin.getBaseWidth()/2);
                    //	mage2.setPosition(pSceneTouchEvent.getX() - mage2.getBaseHeight()/2, pSceneTouchEvent.getY() - mage2.getBaseWidth()/2);
                            
                            return true;
                    }
                    
                    
                 
            });
            
            final Path path = new Path(5)
            	.to(0, CAMERA_HEIGHT - CAMERA_HEIGHT * 0.301f)
            	.to(CAMERA_WIDTH - CAMERA_WIDTH * 0.3f, CAMERA_HEIGHT - CAMERA_HEIGHT * 0.45f)
            	.to(CAMERA_WIDTH - CAMERA_WIDTH * 0.73f, CAMERA_HEIGHT - CAMERA_HEIGHT * 0.6f)
            	.to(CAMERA_WIDTH - CAMERA_WIDTH * 0.32f, CAMERA_HEIGHT - CAMERA_HEIGHT * 0.67f)
            	.to(CAMERA_WIDTH - CAMERA_WIDTH * 0.65f, CAMERA_HEIGHT - CAMERA_HEIGHT * 0.76f);
            
           /* scene.attachChild(new AnimatedSprite(0, CAMERA_HEIGHT - CAMERA_HEIGHT * 0.301f, 20, 20,  textureRegionPoussin));
            scene.attachChild(new AnimatedSprite(CAMERA_WIDTH - CAMERA_WIDTH * 0.3f, CAMERA_HEIGHT - CAMERA_HEIGHT * 0.45f, 20, 20,  textureRegionPoussin));
            scene.attachChild(new AnimatedSprite(CAMERA_WIDTH - CAMERA_WIDTH * 0.72f, CAMERA_HEIGHT - CAMERA_HEIGHT * 0.6f, 20, 20,  textureRegionPoussin));
            scene.attachChild(new AnimatedSprite(CAMERA_WIDTH - CAMERA_WIDTH * 0.32f, CAMERA_HEIGHT - CAMERA_HEIGHT * 0.67f, 20, 20,  textureRegionPoussin));
            scene.attachChild(new AnimatedSprite(CAMERA_WIDTH - CAMERA_WIDTH * 0.65f, CAMERA_HEIGHT - CAMERA_HEIGHT * 0.76f, 20, 20,  textureRegionPoussin));
            */
            poussin.animate(200);
            
            poussin.registerEntityModifier(new PathModifier(33, path, null, new IPathModifierListener() {
            	
              
                public void onPathStarted(final PathModifier pPathModifier, final IEntity pEntity) {
                       // Debug.d("onPathStarted");
                }

                
                public void onPathWaypointStarted(final PathModifier pPathModifier, final IEntity pEntity, final int pWaypointIndex) {
                      //  Debug.d("onPathWaypointStarted:  " + pWaypointIndex);
                        switch(pWaypointIndex) {
                                case 0:
                                	 poussin.animate(new long[]{200, 200, 200, 200}, 4, 7, true);
                                        break;
                                case 1:
                                	 poussin.animate(new long[]{200, 200, 200, 200}, 0, 3, true);
                                        break;
                                case 2:
                                	 poussin.animate(new long[]{200, 200, 200, 200}, 4, 7, true);
                                        break;
                                case 3:
                                	 poussin.animate(new long[]{200, 200, 200, 200}, 0, 3, true);
                                        break;
                                case 4:
                                	 poussin.animate(new long[]{200, 200, 200, 200}, 4, 7, true);
                                        break;
                        }
                }

               
                public void onPathWaypointFinished(final PathModifier pPathModifier, final IEntity pEntity, final int pWaypointIndex) {
                      //  Debug.d("onPathWaypointFinished: " + pWaypointIndex);
                }

               
                public void onPathFinished(final PathModifier pPathModifier, final IEntity pEntity) {
                     //   Debug.d("onPathFinished");
                }
        }, EaseSineInOut.getInstance()));

            scene.attachChild(poussin);
            
            mage.animate(500);
            
         //   mage2.animate(500);
            
         
           
            scene.attachChild(mage);
            
          
          //  scene.attachChild(mage2);


            particleSystem.addParticleInitializer(new ColorInitializer(1, 0, 0));
            particleSystem.addParticleInitializer(new AlphaInitializer(0));
            particleSystem.setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE);
            particleSystem.addParticleInitializer(new VelocityInitializer(-10, 10, -40, -20));
            particleSystem.addParticleInitializer(new RotationInitializer(0.0f, 360.0f));

            particleSystem.addParticleModifier(new ScaleModifier(1.5f, 3.0f, 0, 5));
            particleSystem.addParticleModifier(new ColorModifier(1, 1, 0, 0.5f, 0, 0, 0, 3));
            particleSystem.addParticleModifier(new ColorModifier(1, 1, 0.5f, 1, 0, 1, 4, 6));
            particleSystem.addParticleModifier(new AlphaModifier(0, 1, 0, 1));
            particleSystem.addParticleModifier(new AlphaModifier(1, 0, 5, 6));
            particleSystem.addParticleModifier(new ExpireModifier(6, 6));

          //  particleSystem.
          //  particleSystem.reset();
          //  scene.attachChild(particleSystem);

          //  scene.attachChild(elapsedText);
           // scene.attachChild(fpsText);
            
          
           
            // scene.attachChild(ball);
            
            return scene;
    }

    public void onLoadComplete() {
    	

  
    	 
    }
    
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK)) {
            //(this.getClass().getName(), "back button pressed");
        	
        	
      	  
        }
        return super.onKeyDown(keyCode, event);
    }
    
    @Override
    public void onBackPressed() {
  
    	if(menuPressed) {
    	
    		menuPressed = false;
    		
	    	Toast.makeText(this, "onBack called", Toast.LENGTH_LONG).show();
	    	this.sm.loadMenuInGame();
	    	
	   	
	    	backButton = new Sprite(50, 50, mMenuLeftTextureRegion){
	            public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, final float pTouchAreaLocalX, final float pTouchAreaLocalY) {
	             
	            	this.setAlpha(0.1f);
	            	scene.detachChild(sm.ground);
	            	scene.detachChild(backButton);
	            	scene.detachChild(menuleft);
	            	
	            	scene.unregisterTouchArea(menuleft);
	            	//scene.attachChild(sm.sceneBack);
	            	menuPressed = true;
	            	return true;
	            }
	    	};
	    	
	    	scene.attachChild(backButton);
	    
	    	scene.registerTouchArea(backButton);
	    	
	    	
	    	menuleft = new Sprite(50, 130, mMenuLeftTextureRegion){
	            public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, final float pTouchAreaLocalX, final float pTouchAreaLocalY) {
	             
	            	this.setAlpha(0.1f);
	            	menuPressed = true;
	            	SaveTheMageActivity.this.finish();
	            	
	            	return false;
	            }
	    	};
	    	
	    	scene.attachChild(menuleft);
	    
	    	scene.registerTouchArea(menuleft);
	    	
	    	
	    	
	    	
    	
    	
    	}
    	
    }

}
